package com.example.myapplication.utils;

import com.google.gson.Gson;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RabbitMqUtils {
    public  final static Gson gson =new Gson();
    final static ConnectionFactory factory = new ConnectionFactory();
    final static String MQ_HOST="47.105.162.161";
    final static Integer MQ_PORT=5672;
    final static String USER_NAME="shengyu";
    final static String PASSWD="xzan";
    public final static ExecutorService exec = new ThreadPoolExecutor(20, 50, 6000,
            TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1000));
    static {
        String uri = "CLOUDAMQP_URL";

            factory.setHost(RabbitMqUtils.MQ_HOST);
            factory.setUsername(USER_NAME);
            factory.setPassword(PASSWD);
            factory.setPort(MQ_PORT);
            factory.setAutomaticRecoveryEnabled(false);

    }

    public static void publishToAMQP(String content) {
        try {
            Connection connection = factory.newConnection();
            Channel ch = connection.createChannel();
            ch.confirmSelect();
            if (content == null) {
                content = "";
            }
            try {
                ch.basicPublish("", "event_queue", null, content.getBytes());
                ch.waitForConfirmsOrDie();
            } catch (Exception e) {
                throw e;
            }

        } catch (Exception e) {
            try {
               e.printStackTrace();
                Thread.sleep(5000); //sleep and then try again
            } catch (InterruptedException e1) {
                return;
            }
        }
    }
    public static  void main(String[] args){
        publishToAMQP("dd");
    }
}
